import '@/pages/components/StyleFile/btnStyle.less';
import { Button } from 'devextreme-react';
import notify from 'devextreme/ui/notify';
import React, { useImperativeHandle, useMemo, useRef, useState } from 'react';
import { history, useModel } from 'umi';
import SaveTemplatePopup from '~/public/cpas-business/components-bs/components/TemplatePopup/SaveTemplatePopup';
import CpasTableFs from '~/public/cpas-business/cpas-table/CpasTableFs';
import { CpasIcon } from '~/public/cpas-ui';
import AudTabPage from '~/src/components/PageTab/AudTabPage';
import './index.less';
import { getCpasByCategory, saveTemplateApi } from './service';

import axios from 'axios';
import DropDownButton from 'devextreme-react/drop-down-button';
import SettingFormPupop from './settingFormPupop';

import PopupComponents from '../../FinancialAnalysis/components/Popup';

import { extractFileInfo, Md5_16 } from '@/utils';
import CpasModal from '~/public/cpas-business/cpas-table/CpasModal';
import ChatAnalysisiPupop from '../../FinancialAnalysis/components/chatAnalysisi';

const AnalysisCpasTable = React.forwardRef((props: any, ref: any) => {
  const oldResultdata = useRef<any>([]);
  const audTabpage = AudTabPage.getInstance();
  audTabpage.onClickcloseTabCallBack = async (targetKey: string, action: string) => {
    if (targetKey.includes('trend')) {
      debugger;
      const realrealHandSonGridRefRef = getRealCPASTableRef();
      let data = await realrealHandSonGridRefRef.getCpasTableGrid();
      let newdata = data.data.map((a: any) => {
        return [a[9], a[12]];
      });
      let ischange = false;
      debugger;
      newdata.forEach((e: any, index: number) => {
        if (oldResultdata.current.length) {
          if (
            !(oldResultdata.current[index][0] === e[0] && oldResultdata.current[index][1] === e[1])
          ) {
            ischange = true;
          }
        }
      });

      if (ischange) {
        PopupComponentsRef.current.show({
          title: '提示信息',
          content: '数据修改，未保存。是否保存？',
          cancelText: '否',
          okText: '是',
          okCallback: async () => {
            setSpinLoad(true);
            setLoadingContent('正在保存数据...');
            const resSave = await saveToServer(false);

            if (resSave) {
              notify(`保存成功！`, 'success', 2000);
            } else {
              notify(`保存失败！`, 'error', 2000);
            }
            const p = audTabpage.closeTabByKey(targetKey as string);
            history.push(p as string);
          },
          cancelCallback: () => {
            const p = audTabpage.closeTabByKey(targetKey as string);
            history.push(p as string);
            // PopupComponentsRef.current.closeDia();
          },
        });
      } else {
        const p = audTabpage.closeTabByKey(targetKey as string);
        history.push(p as string);
      }
    } else {
      const p = audTabpage.closeTabByKey(targetKey as string);
      history.push(p as string);
    }
  };
  const {
    CPASTableProps,
    excelParams,
    initloaddataApi,
    commonCpasTableDisplay,
    CPASTableTabName,
    setPageLoading,
  } = props;

  const { CPASTableType, tableName, titleName, origin } = CPASTableProps;
  const { initialState } = useModel('@@initialState');
  const { cpasTableZeroReplace, negationRow } = initialState?.settings;
  const { dbname, bsdw, zcbfid, zcbfName, sjnd } = initialState?.curPart;
  const [rowsMapList, setRowsMapList] = useState<any[]>([]);
  const [columnsMapList, setColumnsMapList] = useState<any[]>([]);
  const cpasTableFsRef = useRef<any>(null);
  const saveTemplatePopupRef = useRef<any>();
  const changeTemplatePopupRef = useRef<any>();
  const [showMenuToolBar, setShowMenuToolBar] = useState<boolean>(true);
  const [spinLoad, setSpinLoad] = useState<boolean>(false);

  // const [visiblePopup, setVisiblePopup] = useState<boolean>(false);
  const refSettingFormPupop = useRef<any>(null);

  const chatAnalysisiPupop = useRef<any>(null);
  const [visibleSetting, setVisibleSetting] = useState<boolean>(false);

  const cpasTableTid = useRef<any>(''); // tid

  const [titleRightText, setTitleRightText] = useState<string>(' ');
  const [titleLeftText, setTitleLeftText] = useState<string>(' ');
  const [titleCenterText, setTitleCenterText] = useState<string>('');

  const [titleYearStr, setTitleYearStr] = useState<string>(' ');

  const [commonCpasTableNot, setCommonCpasTableNot] = useState<string>('handsonToolsHeight');

  const [titleYearExport, setTitleYearExport] = useState<string>(' ');
  const [titleYearExportMin, setTitleYearExportMin] = useState<string>(' ');
  const PopupComponentsRef = useRef<any>(null);
  const [loadingContent, setLoadingContent] = useState<string>('加载中...');
  const [changItemNum, SetChangItemNum] = useState<number>(0);

  const isSave = useRef<any>(false); // tid
  const exportExcelRef = useRef<any>(null);

  /**
   *  按钮点击事件
   */

  const onClickchangItemNumCall = async () => {
    // 过滤展示显著的项目
    const realrealHandSonGridRefRef = getRealCPASTableRef();

    // let data = realrealHandSonGridRefRef.getCpasTableGrid()
    if (changItemNum === 0) {
      notify('无重大变动项', 'error', 2000);
      return;
    }
    let data = await realrealHandSonGridRefRef.loadTableByServer(tableName);
    let d = data.displayData.filter(
      (a: any, b: number) => b === 0 || a.filter((a: any) => a === '显著').length,
    );
    //let dp = data.displayData.filter((a: any) => a.filter((a: any) => a === '显著').length)
    const serverData = { ...data, data: d, displayData: d };

    await realrealHandSonGridRefRef.reloadTable(serverData, 'fs', null, true);
  };

  const onClickPercentagebutton = async () => {
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    let data = await realrealHandSonGridRefRef.getCpasTableGrid();
    let ItemCols = data.cellsMeta.filter((a: any) => a?.col === 1);
    // 直接构建好
    let income: any[] = [],
      Liabilities: any[] = [];
    if (tableName.includes('利润')) {
      data.data.forEach((a: any, index: number) => {
        const Isitem = ItemCols.filter((a: any) => a?.row === index);
        if (Isitem.length) {
          if (a[4]) {
            income.push({
              type: a[1],
              value: parseFloat(a[4]),
              isItem:
                a[1].match(/^ */)[0].length === 1 || Isitem[0]?.custom?.r === 1 ? true : false,
            });
          }
        }
      });
    } else {
      let found: boolean = true,
        liability_found: boolean = true;

      data.data.forEach((a: any, index: number) => {
        const Isitem = ItemCols.filter((a: any) => a?.row === index + 1);
        console.log(Isitem, a[0], a[4], found);
        if (Isitem.length) {
          if (found && a[4] && a[0]) {
            income.push({
              type: a[1],
              value: parseFloat(a[4]),
              isItem:
                a[1].match(/^ */)[0].length === 1 || Isitem[0]?.custom?.r === 1 ? true : false,
            });
          } else {
            //&& !(a[0]?.includes('合计') || a[0]?.includes('总计'))
            if (a[4] && a[0] && liability_found) {
              Liabilities.push({
                type: a[1],
                value: parseFloat(a[4]),
                isItem:
                  a[1].match(/^ */)[0].length === 1 || Isitem[0]?.custom?.r === 1 ? true : false,
              });
            }
          }
          if (a[0]?.includes('资产总计')) {
            found = false; // 找到分
          }
          // if (a[0]?.includes('负债总计')) {
          //   liability_found = false; // 找到分
          // }
        }
      });
    }
    if (income.length || Liabilities.length) {
      chatAnalysisiPupop.current.showPupop(income, Liabilities);
    } else {
      notify('暂无数据', 'error', 2000);
    }
  };

  const onClickExportToDraft = async () => {
    await cpasTableFsRef?.current?.handsonTableFs?.current?.menuToolRef.current?.exportToDraft();
  };

  const loadTableByServerData = async (serverName: string, isRe?: boolean) => {
    let serverData: any;
    let liability;
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    if (realrealHandSonGridRefRef) {
      if (isRe) {
        realrealHandSonGridRefRef.resetTable('fs');
        return;
      }
      setSpinLoad(true);
      setLoadingContent('加载中...');
      console.log('@@@ 获取真是的CPASTable的ref', realrealHandSonGridRefRef);
      try {
        serverData = await realrealHandSonGridRefRef.loadTableByServer(serverName);
        if (serverName.includes('负债')) {
          // let AssentToTle = 0,
          //   Now_AssentToTle = 0;
          // serverData.data.forEach((a: any) => {
          //   if (a[0]?.includes('资产总计')) {
          //     Now_AssentToTle = a[4]; // 找到分
          //     AssentToTle = a[2]; // 找到分
          //   }
          // });
          liability = await realrealHandSonGridRefRef.loadTableByServer(
            serverName.replace('资产', ''),
          );

          //直接两个表 合并显示，
          liability?.displayData.shift();
          liability?.data.shift();
          // const temdata = liability?.data.map((a: any) => {
          //   if (a[2]) {
          //     a[3] = new BigNumber(a[2]).dividedBy(AssentToTle).toFixed(4);
          //   } else if (a[4]) {
          //     a[5] = a[4];
          //     // return a
          //   }
          //   return a;
          // });
          // 原因分析合并
          let conf = liability.cellsMeta.filter((a: any) => a.col === 1);
          conf.forEach((elemen: any, index: number) => {
            if (elemen.row >= 1) {
              serverData.cellsMeta.push({
                ...elemen,
                row: index + serverData.displayData.length - 1,
              });
            }
          });
          // liability.displayData = liability?.displayData.map((a: any) => {
          //   const res = serverData.displayData.filter((b: any) => b[0] === a[0]);
          //   if (res.length) {
          //     a[9] = res[1][9];
          //     a[12] = res[1][12];
          //     return a;
          //   } else {
          //     return a;
          //   }
          // });

          serverData.displayData = serverData.displayData.concat(liability?.displayData);
          serverData.data = serverData.data.concat(liability?.data);
        }
        console.log('--------serverData初始数据 @@@', serverData);
        if (serverData.data) {
          cpasTableTid.current = serverData.tid;

          // 设置只读显示
          serverData.headerColumn = serverData.headerColumn.map((a: any) => {
            return { ...a, config: { ...a.config, readOnly: true } };
          });
          serverData.header = serverData.header.map((a: any) => {
            if (a.children) {
              let children = a.children.map((b: any) => {
                if (!b.label.includes('原因分析')) {
                  return { ...b, config: { ...b.config, readOnly: true } };
                } else {
                  return b;
                }
              });
              return { ...a, children: children, config: { ...a.config, readOnly: true } };
            } else {
              return { ...a, config: { ...a.config, readOnly: true } };
            }
          });

          // 存数据用于推出是对比变化
          oldResultdata.current = [];
          serverData.displayData.forEach((a: any) => {
            oldResultdata.current.push([a[9], a[12]]);
          });
          await realrealHandSonGridRefRef.reloadTable(serverData, 'fs', null, true);
          await saveToServer(false);

          setSpinLoad(false);
          setLoadingContent(' ');
          SetChangItemNum(
            serverData.displayData.filter((a: any) => a.filter((a: any) => a === '显著').length)
              .length,
          );
          console.log('   数据@@@ tid', serverData);
          notify(`获取该表数据成功！`, 'success', 2000);

          return {
            data: serverData,
            msg: serverData.msg,
            success: true,
          };
        } else {
          // setServerDataLen(2);
          notify(`获取数据失败：${serverData.msg}！`, 'warning', 2000);
          setSpinLoad(false);
          setLoadingContent(' ');
          realrealHandSonGridRefRef.resetTable('fs');
          return {
            data: [],
            msg: serverData.msg,
            success: false,
          };
        }
      } catch (e) {
        console.log(e);
        notify(`没有该表:【${serverName}】的数据！`, 'warning', 2000);
        setSpinLoad(false);
        setLoadingContent(' ');
        realrealHandSonGridRefRef.resetTable('fs');
        return {
          data: [],
          msg: `没有该表:【${serverName}】的数据！`,
          success: false,
        };
      }
    }

    return;
  };

  // 获取真是的CPASTable的ref
  const getRealCPASTableRef = () => {
    if (cpasTableFsRef.current) {
      const realHandSonGridRef = cpasTableFsRef.current.handsonTableFs.current;
      return realHandSonGridRef;
    }
    return null;
  };

  /**
   * cpas表格数据存储到线上
   */
  const saveToServer = async (isreolad = true) => {
    const realHandSonGridRef = getRealCPASTableRef();
    if (realHandSonGridRef) {
      try {
        const repeatData: any[] = realHandSonGridRef.gridService.getDataByRmapRepeat(
          realHandSonGridRef.data,
        );
        if (repeatData.length) {
          notify(
            `请修改${origin}报表的${repeatData[0].index.toString()}行的主键，重复主键：${
              repeatData[0].key
            }`,
            'error',
            2000,
          );
          return;
        }
        const Md5_16Str = Md5_16(tableName);
        const res = await realHandSonGridRef.saveToServer(tableName, CPASTableType, Md5_16Str);

        if (res && isreolad) {
          notify(`保存成功！`, 'success', 2000);
          const serverData = await realHandSonGridRef.loadTableByServer(tableName);
          await realHandSonGridRef.reloadTable(serverData, 'fs', null, true);
          return true;
        }
        return res;
      } catch (error) {
        console.log('li', error);
        notify(`保存失败！`, 'error', 2000);
        return false;
      }
    }
    return false;
  };

  const exportExcel = async (isAll: boolean) => {
    let tempExcelDataArr: any = [...excelParams];

    const tempExcelData = tempExcelDataArr.map((itemParam: any, index: number) => {
      if (titleYearStr) {
        itemParam.tableDate = index < 2 ? titleYearExportMin : titleYearExport;
      } else {
        itemParam.tableDate = ' ';
      }
      itemParam.signDirection = 'vertical';
      return itemParam;
    });
    let xlsxName = ' ';
    if (origin === '审定财务') {
      // XXXX公司XXXX年度未审报表趋势分析.xlsx
      xlsxName = `${bsdw}${sjnd}年度审定报表趋势分析`;
    } else {
      xlsxName = `${bsdw}${sjnd}年度未审报表趋势分析`;
    }

    // console.log(tempExcelData, '@@@');
    // 1、单个导出文件名称：未审财务报表+功能页签名，审定财务报表+功能页签名，试算平衡表：年度—试算平衡表—页签名—期初/期末；
    // 2、批量导出：未审财务报表、审定财务报表、年度—试算平衡表；
    //@ts-ignore
    const dialog_result = await window.electronComponents.showSaveDialog(
      'xlsx',
      `${xlsxName}.xlsx`,
    );
    if (!dialog_result.canceled) {
      let radioTable: any = [];
      if (isAll) {
        radioTable = tempExcelData.filter((item: any) => {
          return item.isBatchExport;
        });
      } else {
        radioTable = tempExcelData.filter((item: any) => {
          return item.cpastableParam.tname === tableName;
        });
      }
      // console.log(tempExcelData, radioTable, tableName, '@@@');
      const fileData = extractFileInfo(dialog_result.filePath);
      const params = {
        excelInfo: radioTable,
        dbname,
        directoryPath: fileData.dirName,
        excelFileName: fileData.fileName,
        projectName: bsdw,
      };
      const url = `/cpasApi/cpasTableEngine/getCpatableToBatchExportExcel`;
      const data = await axios.post(url, params);
      if (data.data?.data?.code) {
        return {
          code: data.data.data.code,
          msg: data.data.data.msg,
          ok: data.data.data.ok,
          type: '导出',
        };
      }
      const tempMsg = 'EBUSY: resource busy or locked, open';
      const isTrue = data.data.msg.includes(tempMsg);
      if (isTrue) {
        return {
          code: data.data.code,
          msg: '文件已被程序打开，需要关闭已被打开的文件。',
          ok: data.data.ok,
          type: '导出',
        };
      }
      return {
        code: data.data.code,
        msg: data.data.msg,
        ok: data.data.data,
        type: '导出',
      };
    }
    return {
      code: 404,
      msg: '取消了选择路径！',
      ok: false,
      type: '取消',
    };
  };

  const batchExport = async (isTemp: boolean) => {
    setPageLoading(false);
    const res = await exportExcel(isTemp);
    setPageLoading(true);
    if (res.type === '导出') {
      if (res.ok) {
        notify(`导出成功！`, 'success', 2000);
      } else {
        PopupComponentsRef.current.show({
          title: '提示信息',
          content: res.msg,
          cancelText: '取消',
          okText: '确定',
          okCallback: () => {
            PopupComponentsRef.current.closeDia();
          },
        });
      }
    }
  };

  const getHeaderData = async (curtid: string) => {
    console.log(curtid, '@@@');

    let tempHeader: any = {};
    let tempAlias: any = {};
    const resAlias = await getCpasByCategory({
      dbname,
      tid: [curtid],
      category: 'aliasName',
    });
    if (resAlias.data.length) {
      tempAlias = JSON.parse(resAlias.data[0].describe);
      setTitleCenterText(tempAlias?.headerTitleText ?? '');
    } else {
      setTitleCenterText('');
    }
    const resHeader = await getCpasByCategory({
      dbname,
      tid: [curtid],
      category: 'fsHeader',
    });
    if (resHeader.data.length) {
      tempHeader = JSON.parse(resHeader.data[0].describe);
      if (tempHeader?.hasOwnProperty('headerTitleLeftText')) {
        let leftText = tempHeader.headerTitleLeftText
          ? `${tempHeader.headerTitleLeftText}${bsdw}`
          : ' ';
        setTitleLeftText(leftText);
      }

      if (tempHeader?.hasOwnProperty('headerTitleRightText')) {
        setTitleRightText(tempHeader?.headerTitleRightText ?? ' ');
      } else {
        if (tempHeader) {
          setTitleRightText(tempHeader);
          setTitleLeftText(`编制单位: ${bsdw}`);
        } else {
          setTitleRightText(' ');
          setTitleLeftText(' ');
        }
      }
    } else {
      setTitleLeftText(' ');
      setTitleRightText(' ');
    }
  };
  useImperativeHandle(ref, () => ({
    CPASInit2: async (rundata: string, isTrue: boolean) => {
      await loadTableByServerData(rundata, !isTrue);
      await getHeaderData(cpasTableTid.current);
    },
  }));
  return (
    <div className="commonCpasAnalysisTableBox">
      <div className="btnsTools">
        <Button
          type="default"
          className="defaultBtn"
          onClick={async () => {
            setSpinLoad(true);
            setLoadingContent('正在保存数据...');
            const resSave = await saveToServer();
            if (resSave || !resSave) {
              setTimeout(() => {
                setSpinLoad(false);
                setLoadingContent(' ');
              }, 500);
            }
          }}
          text="保存"
        />
        <Button
          type="default"
          className="defaultBtn"
          onClick={onClickPercentagebutton}
          text="占比分析图"
        />
        {/* <Button
          className="defaultBtnWhite purpleBtnUI"
          onClick={() => {
            setCommonCpasTableNot(commonCpasTableNot === '' ? 'handsonToolsHeight' : '');
          }}
          text="模板设计"
        /> */}
        <DropDownButton
          style={{ height: '30px', margin: '0px 8px 0 4px' }}
          text={'导出'}
          dropDownOptions={{
            width: 180,
          }}
          onItemClick={async (e: any) => {
            if (e.itemData === '导出到Excel文件') {
              batchExport(true);
            } else if (e.itemData === '追加到Excel底稿') {
              await onClickExportToDraft();
            } else if (e.itemData === '导出设置') {
              setVisibleSetting(true);
              refSettingFormPupop.current.showPupop(
                {
                  capsTid: cpasTableTid.current,
                  capsOrigin: origin,
                  capsTabName: CPASTableTabName,
                  capsTitleName: titleCenterText,
                  capsTitleDate: titleYearStr,
                },
                {
                  okCallback: async () => {
                    setVisibleSetting(false);
                    await getHeaderData(cpasTableTid.current);
                  },
                  cancelCallback: () => {
                    setVisibleSetting(false);
                  },
                },
              );
            }
          }}
          items={['导出到Excel文件', '追加到Excel底稿']}
        />

        {/* <DropDownButton
          style={{ height: '30px', marginRight: '4px' }}
          text="模板"
          dropDownOptions={{
            width: 120,
          }}
          onItemClick={async (e: any) => {
            if (e.itemData === '切换模板') {
              // const data = await getSeekAuditReportTemplate({ zcbfid });
              // console.log('当前模板：', data.data.AuditReportTemplate);
              // const templateName = data.data.AuditReportTemplate;
              // changeTemplatePopupRef.current.showTemplate({ templateName });
            } else {
              saveTemplatePopupRef.current.showTemplate();
            }
          }}
          items={['切换模板', '保存模板']}
        /> */}
        <div className="boxRight" />
        <Button
          className="defaultReloadBtnWhite"
          render={() => <CpasIcon type="icon-refresh" fontSize={16} />}
          onClick={async () => {
            await initloaddataApi({ isAllInit: true, yearTableName: tableName, actionTabs: '' });
          }}
        />
      </div>

      <div className={`commonCpasTable ${commonCpasTableDisplay}  ${commonCpasTableNot} `}>
        <div className="formTitleStyle">
          重大变动项目：
          <i className="changItemNum" onClick={onClickchangItemNumCall}>
            {changItemNum}
          </i>
        </div>
        <CpasTableFs
          tabGroup="fs-tab"
          tabLevel={2}
          ieType="json,draft"
          numberZeroReplace={cpasTableZeroReplace}
          type={'fs'}
          name={tableName}
          mapRowsList={rowsMapList}
          mapColumnsList={columnsMapList}
          isShowMenuToolBar={true}
          verifyMode={true}
          notes={{ tid: cpasTableTid.current }}
          // gridData={copyServerData}
          tableDate={titleYearStr}
          tableTitle={titleCenterText}
          tableRiDesc={titleRightText}
          tableLfDesc={titleLeftText}
          isTest={true}
          ref={cpasTableFsRef}
          draftSheetName={titleName}
          oncheckSetok={(fullResult: any) => {
            console.log(fullResult, 'fullResult');
            debugger;
          }}
        />
      </div>
      {/* <CpasTableChangePupop ref={cpasTableChangePupopRef} tableSaveAndReload={saveAndReload} /> */}
      <SaveTemplatePopup
        ref={saveTemplatePopupRef}
        okCallback={async (data: any) => {
          console.log(data, '@@@ 保存模板');
          const res: any = await saveTemplateApi({
            dbName: dbname,
            templateName: data,
            type: 'fs',
            tableNames: ['试算分析-资产负债表_审定', '试算分析-利润表_审定'], //'试算分析-负债表_未审'
          });
          if (res.success) {
            notify('保存成功', 'success', 2000);
          } else {
            notify('保存失败', 'error', 2000);
          }
        }}
        cancelCallback={() => {
          console.log('@@@ ， 取消');
        }}
      />
      {useMemo(() => {
        if (visibleSetting) {
          return <SettingFormPupop ref={refSettingFormPupop} />;
        }
        return <></>;
      }, [visibleSetting])}
      <PopupComponents ref={PopupComponentsRef} />
      <ChatAnalysisiPupop ref={chatAnalysisiPupop} type={tableName} />
      <CpasModal
        ref={exportExcelRef}
        type="fs"
        zcbfid={zcbfid}
        zcbfName={zcbfName}
        exportSort={['资产表', '负债表', '利润表', '现金流量表', '现金流补充资料表']}
      />
    </div>
  );
});
export default React.memo(AnalysisCpasTable);
